﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using AKMII.DMRA.Common;
using AKMII.DMRA.DataAccess;
using AKMII.DMRA.Business.Rule;

namespace AKMII.DMRA.DataLoader
{
    public class Uploader
    {
        private bool Upload(string file, string fileName, string type)
        {
            try
            {
                if (file != null)
                {
                    if (type.Equals("PrintingHouse", StringComparison.CurrentCultureIgnoreCase))
                    {
                        FtpUtils.Upload(file, SystemConfiguration.CommonSetting.PrintingHouseFtp + "/" + fileName,
                            SystemConfiguration.CommonSetting.PrintingHouseUserName, SystemConfiguration.CommonSetting.PrintingHousePassword, false);
                    }
                    else if (type.Equals("DMRA", StringComparison.CurrentCultureIgnoreCase))
                    {
                        FtpUtils.Upload(file,SystemConfiguration.CommonSetting.UploadFtp + "/" + fileName,
                            SystemConfiguration.CommonSetting.FtpUserName, SystemConfiguration.CommonSetting.FtpPassword, true);
                    }
                    else
                    {
                        // Noting to do
                    }
                }
                else
                {
                    throw new ArgumentException("unsupport file type: " + file);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occurs in upload process", ex);
                Mail email = new Mail();
                email.Subject = string.Format(Constants.MailSubjectException, "upload file");
                email.Content = string.Format(Constants.MailContentException, "upload files", DateTime.Now.ToString(), " the upload server inaccessible,etc");
                UserAccessor accessor = new UserAccessor();
                email.Recipients=accessor.GetMailAddress(UserType.Administrator);
                Utility.Send(email);
                return false;
            }

            return true;
        }

        public void Process()
        {
            CommandHistoryAccessor accessor = new CommandHistoryAccessor();
            DateTime dateTime = accessor.GetLastExecuteTime(Command.Upload.ToString());
            DirectoryInfo di = null;
            FileInfo[] fi = null;

            #region Upload file to DMRA

            di = new DirectoryInfo(SystemConfiguration.CommonSetting.FolderForEncryptDmraFile);
            fi = di.GetFiles("*.pgp");

            foreach (FileInfo file in fi)
            {
                if (file.LastWriteTime > dateTime)
                {
                    Logger.Info("Start upload " + file.Name);

                    Upload(Path.Combine(SystemConfiguration.CommonSetting.FolderForEncryptDmraFile, file.Name),
                        file.Name, "DMRA");

                    Logger.Info("Finish upload " + file.Name);
                }
            }

            #endregion

            #region Upload file to Printing House

            di = new DirectoryInfo(SystemConfiguration.CommonSetting.FolderForEncryptPrintingHouseFile);
            fi = di.GetFiles();
            ZipAccessor zipAccess = new ZipAccessor();
            foreach (FileInfo file in fi)
            {
                if (file.LastWriteTime > dateTime)
                {
                    Logger.Info("Start upload " + file.Name);
                    if (Upload(Path.Combine(SystemConfiguration.CommonSetting.FolderForEncryptPrintingHouseFile, file.Name),
                        file.Name, "DMRA"))
                    {
                        Logger.Info("Start send confirmation mail for DMRA file to " + Constants.OrderSummaryMailRecipts);
                        Mail email = new Mail();
                        LeadBlock zip = zipAccess.GetLeadBlcokTypesCount(CurrentPeriod.Year.ToString(), CurrentPeriod.Month.ToString());

                        StringBuilder text = new StringBuilder(string.Empty);
                        text.Append("ActiveCount: " + zip.ActiveLeadCount.ToString() + "\r\n");
                        text.Append("LapsedCount: " + zip.LapsedLeadCount.ToString() + "\r\n");
                        text.Append("BusinessCount: " + zip.BusinessLeadCount.ToString() + "\r\n");
                        text.Append("NeighborCount: " + zip.NeighborLeadCount.ToString() + "\r\n");
                        text.Append("TotalCount: " + (zip.NeighborLeadCount + zip.BusinessLeadCount + zip.ActiveLeadCount + zip.LapsedLeadCount).ToString() + "\r\n");
                       
                        email.Subject = string.Format(Constants.MailSubjectOrderSummary,
                            Utility.GetMonthName(CurrentPeriod.Month) + "&" + CurrentPeriod.Year);
                        email.Content = string.Format(Constants.MailContentOrderSummary,
                            Utility.GetMonthName(CurrentPeriod.Month), Convert.ToString(Math.Floor(file.Length / 1024.0) + 1) + " KB", text.ToString());
                        List<string> mailAddress = new List<string>();

                        foreach (string address in Constants.OrderSummaryMailRecipts.Split(';'))
                        {
                            mailAddress.Add(address);
                        }

                        email.Recipients = mailAddress;
                        Utility.Send(email);
                        Logger.Info("Finish send confirmation mail for DMRA file to " + Constants.OrderSummaryMailRecipts);
                    }
                    Logger.Info("Finish upload " + file.Name);
                }
            }

            #endregion

            accessor.UpdateLastExecuteTime(Command.Upload.ToString(), DateTime.Now);
        }
    }
}
